<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-button type="primary" @click="addRoles">添加角色</el-button>
      <!-- 表格区域 -->
      <el-table :data="roleslist" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="center" :class="['bdbottom', i1 === 0 ? 'bdtop' : '']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限列表 -->
              <el-col :span='5'>
                <el-tag>  {{item1.authName}} </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和二级权限列表 -->
              <el-col :span='19'>
                <el-row class="center" :class="[i2 === 0 ? '' : 'bdtop']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!-- 二级权限列表 -->
                  <el-col :span="6">
                    <el-tag type="success">  {{item2.authName}} </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                    <!-- 三级权限列表 -->
                  <el-col :span="18">
                    <el-tag closable @close='deleteTag(scope.row, item3.id)' v-for="(item3) in item2.children" :key="item3.id" type="warning">  {{item3.authName}} </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="addRolesAlter(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="fenpeiRoles(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框区域 -->
    <el-dialog
    title="添加角色"
    :visible.sync="dialogRoles"
    width="50%" @close='rolesClose'>
      <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px" >
         <el-form-item label="角色名称" prop="roleName" >
           <el-input v-model="rolesForm.roleName"></el-input>
         </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="rolesForm.roleDesc"></el-input>
         </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRoles = false">取 消</el-button>
          <el-button type="primary" @click='rolesFormTj'>确 定</el-button>
        </span>
    </el-dialog>
    <!-- 编辑角色对话框区域 -->
    <el-dialog
    title="编辑角色"
    :visible.sync="dialogRolesAlter"
    width="50%" @close='rolesCloseAlter'>
      <el-form :model="rolesFormAlter" :rules="rolesFormAlterRules" ref="rolesFormAlterRef" label-width="100px" >
         <el-form-item label="角色名称" prop="roleName" >
           <el-input v-model="rolesFormAlter.roleName"></el-input>
         </el-form-item>
         <el-form-item label="角色描述" prop="roleDesc">
           <el-input v-model="rolesFormAlter.roleDesc"></el-input>
         </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRolesAlter = false">取 消</el-button>
          <el-button type="primary" @click="rolesFormAlterTj">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
    title="分配权限"
    :visible.sync="dialogRolesFenpei"
    width="50%" @close='setRightDialogClosed'>
        <!-- 树形控件 -->
        <el-tree node-key="id" default-expand-all :default-checked-keys='keysRoles' show-checkbox :data="treeRoles" :props="defaultRoles" ref="treeFer"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogRolesFenpei = false">取 消</el-button>
          <el-button type="primary" @click="dialogTree">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleslist: [],
      // 控制添加角色对话框显示与隐藏
      dialogRoles: false,
      //   添加角色列表
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      //   添加角色的表单验证对象
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      //   控制编辑角色对话框的显示与隐藏
      dialogRolesAlter: false,
      // 编辑角色列表
      rolesFormAlter: '',
      //   便捷角色的表单验证
      rolesFormAlterRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      //   分配权限对话框显示与隐藏
      dialogRolesFenpei: false,
      //   权限数据源
      treeRoles: [],
      //   树状控件绑定对象
      defaultRoles: {
        label: 'authName',
        children: 'children'
      },
      //   默认勾选的节点id数组
      keysRoles: [],
      arrTree: ''
    }
  },
  created() {
    // 获取所有角色
    this.getRolesList()
  },
  methods: {
    // 获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist = res.data
    },
    // 添加角色按钮
    addRoles() {
      this.dialogRoles = true
    },
    // 监听添加角色对话框关闭事件
    rolesClose() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 提交添加的角色数据发起请求并进行预验证
    rolesFormTj() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return
        // 发起网路请求
        const { data: res } = await this.$http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.dialogRoles = false
        this.getRolesList()
      })
    },
    // 编辑角色按钮
    async addRolesAlter(id) {
      // console.log(id)
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.rolesFormAlter = res.data
      //   console.log(res.data);
      this.dialogRolesAlter = true
    },
    rolesCloseAlter() {
      this.$refs.rolesFormAlterRef.resetFields()
    },
    rolesFormAlterTj() {
      this.$refs.rolesFormAlterRef.validate(async valid => {
        if (!valid) return
        // 发起网路请求
        // console.log(this.rolesFormAlter);
        const { data: res } = await this.$http.put('roles/' + this.rolesFormAlter.roleId, {
          roleName: this.rolesFormAlter.roleName,
          roleDesc: this.rolesFormAlter.roleDesc
        })
        if (res.meta.status !== 200) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.dialogRolesAlter = false
        this.getRolesList()
      })
    },
    // 删除角色
    async deleteRoles(id) {
      //   询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 确认删除用户 发起请求
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      // 刷新页面
      this.getRolesList()
    },
    // 从tag删除角色权限
    async deleteTag(aid, bid) {
      //   询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用确认删除，则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 确认删除用户 发起请求
      const { data: res } = await this.$http.delete(`roles/${aid.id}/rights/${bid}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      // 刷新页面
      aid.children = res.data
    },
    // 点击分配权限按钮事件
    async fenpeiRoles(role) {
      this.arrTree = role.id
      //   发起网络请求获取权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户权限失败')
      }
      this.treeRoles = res.data
      //   console.log(this.treeRoles)
      // 调用递归函数
      this.getkeysRoles(role, this.keysRoles)
      this.dialogRolesFenpei = true
    },
    // 利用递归函数选择出所有三级节点
    getkeysRoles(node, arr) {
      if (!node.children) {
        // 如果当前节点不包含children则为三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getkeysRoles(item, arr))
    },
    // 监测到分配权限对话框关闭事件
    setRightDialogClosed() {
      this.keysRoles = []
    },
    // 点击确定发起网路请求
    async dialogTree() {
      const str = [
        ...this.$refs.treeFer.getCheckedKeys(),
        ...this.$refs.treeFer.getHalfCheckedKeys()
      ]
      const arr = str.join(',')
      const { data: res } = await this.$http.post(`roles/${this.arrTree}/rights`, { rids: arr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.dialogRolesFenpei = false
    }
  }
}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .center {
    display: flex;
    align-items: center;
  }
</style>
